var router = require("koa-router")();
var utils = require("./../utils/utils");
const linkList = require("./../models/defaultlinkSchema");

// 模块导入
var superagent = require("superagent"); //是个 http 方面的库，可以发起 get 或 post 请求。
var cheerio = require("cheerio"); //Node.js 版的 jquery，用来从网页中以 css selector 取数据，使用方式跟 jquery 一样一样的。

router.prefix("/favor");

router.get("/info", async (ctx, next) => {
  try {
    let { name, url } = ctx.query;
    let [title, icon] = await Promise.all([getTitle(url), getIcon(url)]);

    if (!icon) {
      console.log(1, name, 2, url, 3, title, 4, icon);
      icon = "assets/minaqsy.png";
      name = name == "" ? title : name;
      ctx.body = utils.success({
        icon: icon,
        name,
        state: 2,
        url,
      });
    } else {
      // 判断name is empty
      name = name == "" ? title : name;
      ctx.body = utils.success({
        icon: icon.slice(1),
        name,
        state: 1,
        url,
      });
    }
  } catch (error) {
    ctx.body = utils.fail(error);
  }
});

function getIcon(url) {
  return new Promise((resolve, reject) => {
    superagent.get(url).end((e, res) => {
      try {
        var $ = cheerio.load(res.text);
        const data = $(`link[rel*="shortcut icon"]`).attr("href");
        // console.log("data=>", data);
        resolve(data);
      } catch (error) {
        console.log(error);
        resolve({ success: error });
      }
    });
  });
}
function getTitle(url) {
  return new Promise((resolve, reject) => {
    superagent.get(url).end((e, res) => {
      try {
        var $ = cheerio.load(res.text);
        const data = $("title").text();
        // console.log("data=>", data);
        resolve(data);
      } catch (error) {
        console.log(error);
        resolve({ success: error });
      }
    });
  });
}

router.get("/defaultlink", async (ctx, next) => {
  try {
    const res = await linkList.find();
    ctx.body = utils.success(res);
  } catch (error) {
    ctx.body = utils.fail(error);
  }
});
module.exports = router;
